package com.pinhuba.bams.view;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.pinhuba.bams.R;
import com.pinhuba.bams.framework.util.FileUtils;
import com.pinhuba.bams.framework.util.Loger;
import com.pinhuba.bams.framework.util.SharePrefsHelper;
import com.pinhuba.bams.framework.util.ToastHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class ViewFileActivity extends Activity {
	private List<Map<String, Object>> list = null;
	private ListView listView;
	private TextView currentPathTv;
	private TextView confirmTv;
	private TextView addDirTv;
	private TextView backTv;
	private static int lastClickPos;
	private FileAdapter fileadapter;
	private static String curPath;
	private FileUtils fileUtils;
	private SharePrefsHelper spHelper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.viewfiles);
		initView();
		if (initData()) {
			viewFile(Environment.getExternalStorageDirectory().getAbsolutePath());
			setListener();
			fileadapter = new FileAdapter();
			if (!list.isEmpty())
				listView.setAdapter(fileadapter);
		} else {
			currentPathTv.setText(R.string.empty_no_card);
		}

	}

	private void initView() {
		listView = (ListView) findViewById(R.id.viewfile_listview);
		confirmTv = (TextView) findViewById(R.id.viewfiles_confirm_tv);
		addDirTv = (TextView) findViewById(R.id.viewfiles_adddir_tv);
		backTv = (TextView) findViewById(R.id.viewfiles_back_tv);
		currentPathTv = (TextView) findViewById(R.id.viewfile_path_tv);
	}

	private boolean initData() {
		lastClickPos = -1;
		curPath = Environment.getExternalStorageDirectory().getAbsolutePath();
		list = new ArrayList<Map<String, Object>>();
		fileUtils = new FileUtils();
		spHelper = new SharePrefsHelper(this);
		return fileUtils.isSDExist();
	}

	private void setListener() {
		confirmTv.setOnClickListener(bottomBtnListener);
		addDirTv.setOnClickListener(bottomBtnListener);
		backTv.setOnClickListener(bottomBtnListener);
		listView.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
				Loger.d("the position is:" + position + ";The LastClickPos is :" + lastClickPos);
				if (position == 0 || lastClickPos == position) {
					Loger.d("the curpath is:" + curPath);
					if (position == 0) {
						if (curPath.equals(Environment.getExternalStorageDirectory().getAbsolutePath())) {
							Toast.makeText(ViewFileActivity.this, R.string.alreadyparent, Toast.LENGTH_SHORT).show();
							lastClickPos = position;
						} else {
							File file = new File(curPath);
							String strfile = file.getParent();
							Loger.d("the strfile parent is:" + strfile);
							viewFile(strfile);
							fileadapter.notifyDataSetChanged();
						}
					} else {
						Map<String, Object> map = list.get(position);
						String strfile = curPath + "/" + map.get("fileName").toString();
						Loger.d("the child is:" + strfile);
						viewFile(strfile);
						fileadapter.notifyDataSetChanged();
					}
				} else {
					Loger.d("the other is:" + curPath);
				
					Map<String, Object> map = list.get(position);
					if (lastClickPos > 0) {
						map = list.get(lastClickPos);
						map.put("isVisible", false);
					}
					map = list.get(position);
					map.put("isVisible", true);
					fileadapter.notifyDataSetChanged();
					lastClickPos = position;
				}

			}
		});
	}

	AlertDialog ad;
	View layout;
	private OnClickListener bottomBtnListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.viewfiles_confirm_tv:
				spHelper.setSavePath(curPath + "/");
				ViewFileActivity.this.finish();
				break;
			case R.id.viewfiles_adddir_tv:
				Builder bd = new Builder(ViewFileActivity.this);
				LayoutInflater inflater = getLayoutInflater();
				layout = inflater.inflate(R.layout.viewfile_new_dir, (ViewGroup) findViewById(R.id.viewfile_dialog));
				bd.setTitle(R.string.new_dir).setView(layout).setIcon(android.R.drawable.ic_dialog_info).setPositiveButton(R.string.confirm, confirmListener)
						.setNegativeButton(R.string.cancel, cancelListener);

				ad = bd.create();
				ad.show();
				break;
			case R.id.viewfiles_back_tv:

				if (curPath.equals(Environment.getExternalStorageDirectory().getAbsolutePath())) {
					ViewFileActivity.this.finish();
				} else {
					File file = new File(curPath);
					String strfile = file.getParent();
					Loger.d("the strfile parent is:" + strfile);
					viewFile(strfile);
					fileadapter.notifyDataSetChanged();
				}
				break;
			default:
				break;
			}
		}
	};

	private DialogInterface.OnClickListener confirmListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			EditText et = (EditText) layout.findViewById(R.id.etname);
			String str = et.getText().toString();
			if (str.equals("")) {
				ToastHelper.showShortMsg(R.string.dir_name_can_not_empty);
			} else {
				if (fileUtils.isSDExist()) {
					if (fileUtils.SDMakeDir(curPath + "/" + str)) {
						fileadapter.addData(str);
						fileadapter.notifyDataSetChanged();
					} else {
						ToastHelper.showShortMsg(R.string.same_dir_name);
					}
				}
			}
		}
	};

	private DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			ad.dismiss();
		}
	};

	private void viewFile(String path) {
		if (fileUtils.isSDExist()) {
			File root = new File(path);
			if (root.exists()) {
				Loger.d("root exists");
				File[] files = root.listFiles(ff);
				FillData(files);
				curPath = path;
				lastClickPos = -1;
				currentPathTv.setText(curPath);
			}
		}
	}

	private void FillData(File[] files) {
		if (list != null) {
			list.clear();
			for (int i = 0; i < files.length; i++) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("fileName", files[i].getName());
				map.put("isVisible", false);
				list.add(map);
			}
			sortData();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("fileName", "返回上级");
			map.put("isVisible", false);
			list.add(0, map);
			Loger.d("The list size is: " + list.size());
		}
	}

	private void sortData() {
		if (!list.isEmpty()) {
			Collections.sort(list, new Comparator<Map<String, Object>>() {

				@Override
				public int compare(Map<String, Object> object1, Map<String, Object> object2) {
					return object1.get("fileName").toString().compareTo(object2.get("fileName").toString());
				}
			});
		}
	}

	private class FileAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			if (list.isEmpty())
				return 0;
			else
				return list.size();
		}

		@Override
		public Object getItem(int position) {
			if (list.isEmpty())
				return null;
			else
				return list.get(position);
		}

		public void addData(String str) {
			list.get(lastClickPos).put("isVisible", false);
			lastClickPos = -1;
			list.remove(0);
			HashMap<String, Object> hm = new HashMap<String, Object>();
			hm.put("fileName", str);
			hm.put("isVisible", false);
			list.add(hm);
			sortData();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("fileName", "返回上级");
			map.put("isVisible", false);
			list.add(0, map);
		}

		@Override
		public long getItemId(int position) {
			if (list.isEmpty())
				return -1;
			else
				return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (list.isEmpty()) {
				return null;
			} else {
				if (convertView == null) {
					convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.viewfile_item, null);
				}
				TextView tv = (TextView) convertView.findViewById(R.id.file_item_tv);
				ImageView iv = (ImageView) convertView.findViewById(R.id.file_item_right_iv);
				Map<String, Object> map = list.get(position);
				tv.setText(map.get("fileName") == null ? "No name" : map.get("fileName").toString());
				if (map.get("isVisible") == null ? false : (Boolean) map.get("isVisible")) {
					iv.setVisibility(View.VISIBLE);
				} else {
					iv.setVisibility(View.INVISIBLE);
				}
				return convertView;
			}
		}

	}

	private FileFilter ff = new FileFilter() {

		@Override
		public boolean accept(File pathname) {
			return pathname.isDirectory() && !pathname.isHidden();
		}
	};

}
